package com.citybox.infrastructure.user.persistence.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.citybox.domain.user.UserDo;
import com.citybox.infrastructure.user.dataobject.User;
import com.citybox.infrastructure.user.persistence.mapper.UserMapper;
import com.citybox.infrastructure.user.persistence.service.UserService;
import com.citybox.shared.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author zhao.x
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {



    @Transactional
    @Override
    public UserDo findOrCreateUser(String openId, String unionId) {
        UserDo userDo = this.findByOpenId(openId);
        if(userDo == null){
            User newUser = new User();
            newUser.setOpenId(openId);
            newUser.setUnionId(unionId);
            newUser.setNickName("微信用户");
            newUser.setCreateTime(new Date());
            boolean save = super.save(newUser);
            log.info("New user created: {} - {} - {}", newUser.getId(), newUser.getNickName(),save);

            UserDo newUserDo = new UserDo();
            newUserDo.setId(newUser.getId());
            newUserDo.setNickName(newUser.getNickName());
            return newUserDo;
        }
        return userDo;

    }

    @Override
    public UserDo findByOpenId(String openid) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenId,openid);
        User user = this.getBaseMapper().selectOne(wrapper);
        if(user == null){
            log.info("未找到openid为 {} 的用户", openid);
            return null;
        }

        UserDo userDo = new UserDo();
        userDo.setId(user.getId());
        userDo.setNickName(user.getNickName());

        return userDo;

    }

    @Override
    public UserDo findById(String userId) {
        if(StringUtils.isEmpty(userId)){
            return null;
        }
        User byId = super.getById(userId);
        UserDo userDo = new UserDo();
        userDo.setId(byId.getId());
        userDo.setNickName(userDo.getNickName());
        return userDo;
    }
}
